package de.fsujena.chat_pi.client;

import java.io.*;
import java.net.*;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.lang.String;

import de.fsujena.chat_pi.connection.*;
import de.fsujena.chat_pi.message.*;
import de.fsujena.chat_pi.message.SysMessage.CATEGORY;
import de.fsujena.chat_pi.message.SysMessage.MESSAGE;
import de.fsujena.chat_pi.user.User.ROLE;




public class ConnectionThread extends Thread {
	public InputStream in = null;
	public OutputStream out = null;
	public boolean greeting=false;
	public boolean reading=false;
	public boolean loggedIn=false;
	public String username;
	public String newusername;
	public String newpassword;
	public String password;
	public Client mainThread;
	//BufferedReader input = new BufferedReader(new InputStreamReader(System.in));	

	Socket server;
	List<TextMessage> msgArray=new ArrayList<TextMessage>();
	Connector connector;
	// Console console = System.console();
	Console console = null;								//reference to the system console(not really needed)

	

	/**
	 * creates new Thread and connects to the server
	 * @param ip	ip of the server
	 * @param port	port on which the server runs
	 * @throws IOException if there is an error setting up the new connection to the server
	 * @throws RSAException if there is an error setting up the RSA encryption
	 */
	public ConnectionThread(String ip, int port) throws IOException, RSAException {
		server = new Socket(ip, port);
		connector=new Connector(server,true,true);			
		connector.init();
		
	}

	/* (non-Javadoc)
	 * @see java.lang.Thread#run()
	 */
	/* (non-Javadoc)
	 * @see java.lang.Thread#run()
	 */
	/**
	 * Receives the messages and processes them
	 */
	public void run() {
		
		reading=true;										//Enables the loop
		while (reading) {									//the loop
			
			Object inputObject;
				try {
					inputObject = connector.readGeneralObject();	//reading the Object from the server		
				

			if (inputObject instanceof TextMessage){				//check if its a textmessage
				TextMessage tempObj= (TextMessage)inputObject;		//cast into textmessage
				tempObj.setReceived(new Date());					//save the date
				System.out.println("["+tempObj.getSenderUsername()+"] "+tempObj.getMessageText());	//print the message
				msgArray.add(tempObj);								//save the message
				saveHistory();
				}	
			else if (inputObject instanceof SysMessage) {			//check if its a systemmessage
				
				SysMessage sysMessage = (SysMessage) inputObject;	//casting
				switch(sysMessage.getCategory()){
				case ERROR:
					error(sysMessage);
					break;
				case REGISTRATION:
					registration(sysMessage);
					break;
				case STATUS:
					status(sysMessage);
					break;
				case LOGIN:
					login(sysMessage);
					break;
				case CONNECTION:
					connection(sysMessage);
					break;
				case CHANGE_USERNAME:
					change_username(sysMessage);
					break;
				case CHANGE_PASSWORD:
					change_password(sysMessage);
					break;
				case ADMIN:
					admin(sysMessage);
					break;
				case MODERATE:
					moderate(sysMessage);
					break;
				default:
					break;
				}
				/*
				switch (sysMessage.getMessage()) {					//check the content of the message
				case REQUEST_USERNAME:								//server request the username
					sendSysMessage(CATEGORY.LOGIN,MESSAGE.SEND_USERNAME,username);	//send username to the server
					break;
				case REQUEST_PASSWORD:								//server request password
					sendSysMessage(CATEGORY.LOGIN,MESSAGE.SEND_PASSWORD,password);	//send the password to the server
					break;
				case CONNECTED:										//server confirms that the client is connected
					System.out.println("connected to server "+server.getInetAddress()+" on port:"+server.getPort());	//tell that to the user
					break;
				case NOT_LOGGED_IN:									//user is not logged in
					System.out.println("not logged in please log in or register");	//tell that to the user
					break;
				case USERNAME_UNKNOWN:								//Unknown username
					System.out.println("user unknown please register");				//requst an other name
					break;
				case LOGGED_IN:										//server confirms login
					System.out.println("your are now logged in");	//tell the user
					break;
				case PASSWORD_WRONG:								//wrong password
					System.out.println("incorrect password please try to login again");	//request a new login
					break;
				case REQUEST_NEW_USERNAME:						//request new username (after regristration)
					sendSysMessage(CATEGORY.REGISTRATION, MESSAGE.SEND_NEW_USERNAME, username);	//send the new name
					break;
				case REQUEST_NEW_PASSWORD:							//request new password (after regristration)
					sendSysMessage(CATEGORY.REGISTRATION, MESSAGE.SEND_NEW_PASSWORD, password);	//send new password
					break;
				case REGISTRATION_SUCCESSFUL:						//server confirms registration
					System.out.println("Your registration was successful. Please login now using your new username.");	//tell that to the user
					break;
				case SEND_USER_LIST:								//server sends the list of user
					if (sysMessage.getMessageObject() instanceof String[]) {
						String[] userList = (String[]) sysMessage.getMessageObject();
						System.out.printf("Users currently logged in: %s\n", Arrays.toString(userList));	//prints list of user
					}
					break;
				case DISCONNECTED:									//a user disconnected
					System.out.println("["+sysMessage.getMessageString()+"] disconnected");	//tell that to the user
					break;
				case ALREADY_LOGGED_IN:								//this client is already logged in
					System.out.println("you are already logged in");//tell the user
					break;
				case USERNAME_ALREADY_EXISTS:						//username already in use (during registration process)
					System.out.println("username already in use try an other one");	//tell the user
					break;
				case LOGGED_OUT:									//a user loggeged out
					System.out.println("["+sysMessage.getMessageString()+"] logged out");//tell the user
					break;
				case USER_ALREADY_LOGGED_IN:						//an other client is already logged in with this name
					System.out.println("this user is already logged in please try an other name");	//tell the user
					break;
				case NEW_USER_INFO:									//info about new user connected
					System.out.println(sysMessage.getMessageString()+" just connected");	//tell the user
					break;
				case KICK_USER:
					if(sysMessage.getMessageString().equals(username)) {
						this.mainThread.isconnected = false;
						System.out.println("you are kicked by "+sysMessage.getSenderUsername());
					} else System.out.println("user "+sysMessage.getMessageString()+" was kicked by "+sysMessage.getSenderUsername());
					break;
				case BANN_USER:
					if(sysMessage.getMessageString().equals(username)) {
						this.mainThread.isconnected = false;
						System.out.println("you were banned from the server by "+sysMessage.getSenderUsername());
					} else System.out.println("user "+sysMessage.getMessageString()+" was banned from the server by "+sysMessage.getSenderUsername());
					break;
				case UNBANN_USER:
					if(sysMessage.getMessageString().equals(username))
						System.out.println("you were unbanned from the server by "+sysMessage.getSenderUsername());
					else System.out.println("user "+sysMessage.getMessageString()+" was unbanned from the server by "+sysMessage.getSenderUsername());
					break;
				case NO_ADMIN:
					System.out.println("you need to be a admin to do this");
					break;
				case NO_MOD:
					System.out.println("you need to be a moderator to do this");
					break;
				case YOU_ARE_REMOVED:
					System.out.println("you are no longer registerd on the server");
					break;
				case USERNAME_BANNED:
					System.out.println("this username is banned from the server");
					break;
				case REQUEST_CHANGED_USERNAME:						//request new password (after change of password)
					sendSysMessage(CATEGORY.CHANGE_USERNAME, MESSAGE.SEND_CHANGED_USERNAME, newusername);	//send the new password
					break;
				case REQUEST_CHANGED_PASSWORD:
					sendSysMessage(CATEGORY.CHANGE_PASSWORD, MESSAGE.SEND_CHANGED_PASSWORD, newpassword);	//send the new password
					break;
				case USERNAME_CHANGED:
					if(sysMessage.getSenderUsername().equals("SERVER")){
						System.out.println("your username was changed to "+sysMessage.getMessageString());
						username=sysMessage.getMessageString();
						newusername="";
					}else{
						System.out.println(sysMessage.getSenderUsername()+" changed his name to "+sysMessage.getMessageString());
					}
					break;
				case PASSWORD_CHANGED:
					System.out.println("your password was changed");
					password=newpassword;
					newpassword="";
					break;
				case TYPE_PASSWORD:
					String tempstr=null;
					tempstr=getPassword();
					System.out.println("4");
					System.out.println(tempstr);
					System.out.println("5");
					sendSysMessage(CATEGORY.LOGIN,MESSAGE.SEND_PASSWORD,tempstr);			//let the user type in the password
					break;
				default:
					break;
				}
				*/			
			} else if (inputObject instanceof String){				//if string object(shouldn't happen)
				String temp=(String)inputObject;
				if (temp.isEmpty()==false)							//if not empty
					System.out.printf(temp);						//print it's content


				
			}
				} catch (ClassNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {							//catch exception on error (e.g.if connection to server is interrupted)
					//e.printStackTrace();
					if(reading){									//only true if connection lost unexpected
					reading=false;									//stops loop
					System.err.println("lost connection to server");//print error to the user
					try {
						server.close();								//close the socket
						server=null;								//free resources
					} catch (IOException e1) {
						e1.printStackTrace();
					}
					this.disconnect();								//stop thread
					}
				}
							
		}

	}

	/**
	 * send a message object to the server
	 * @param msg message object to send
	 */
	public void sendMessage(Message msg) {
		try {
			connector.sendMessageObject(msg);				//sends message
		} catch (IOException e) {
			//e.printStackTrace();
			System.err.println("Error sending message.");	//print error 
		}		
		return;
	}

	/**
	 * stops the thread and free recources
	 */
	public void disconnect() {
		reading=false;								//stops the reading loop
		try {
			if(server!=null)this.server.close();	//check if server isn't already closed and close it if not
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			this.finalize();						//call garbage collector
		} catch (Throwable e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return;
	}

	
	/**
	 * sends system message to the server
	 * @param cat	category of the message
	 * @param msg	messagecode
	 */
	public void sendSysMessage(SysMessage.CATEGORY cat, SysMessage.MESSAGE msg) {
		SysMessage sysMsg = new SysMessage(cat, msg);		//create message object
		sysMsg.setSent(new Date());							//write date
		sysMsg.setSenderUsername(username);					//set username
		try {
			connector.sendMessageObject(sysMsg);			//send message
		} catch (IOException e) {
			e.printStackTrace();
			System.err.println("Error sending message.");	//print error otherwise
		}
	}
	
	/**
	 * sends system message to the server
	 * @param cat	category of the message
	 * @param msg	messagecode
	 * @param msgStr string message of the systemmessage
	 */
	public void sendSysMessage(SysMessage.CATEGORY cat, SysMessage.MESSAGE msg, String msgStr) {
		SysMessage sysMsg = new SysMessage(cat, msg, msgStr);	//create message object
		sysMsg.setSent(new Date());								//write date
		sysMsg.setSenderUsername(username);						//set username
		try {
			connector.sendMessageObject(sysMsg);				//send message
		} catch (IOException e) {
			e.printStackTrace();
			System.err.println("Error sending message.");		//print error otherwise
		}
	}
	/**
	 * aks the user about the password
	 * @param newuser flag if a new user
	 * @return	string containing the password
	 */
	public String getPassword() {
	//TODO find out why the hell this doesn't work (hint readline doesn't work)
		System.out.println("Enter Password:");		//ask for the password
		String passwd=null;
		try {
			System.out.println("1");
			//if (console != null) {								//only if there actually is a console (there is no console in eclipse)
				//passwd = new String(console.readPassword());	//read password from console with masked characters
				//return passwd;
		//	} else {
				passwd= mainThread.input.readLine();						//without console read as standard input
				
				System.out.println("2");
				return passwd;
				
			//}
			
		} catch (Exception e) {
			e.printStackTrace();
			return "bob";
		}

	}
	
	/**
	 * process sysmessages with category error
	 * @param sysMessage message to process
	 */
	public void error(SysMessage sysMessage){
		switch(sysMessage.getMessage()){
		case MSG_NOT_EXPECTED:
			System.out.println("message unexpected");
			break;
		case WRONG_MSG_TYPE:
			System.out.println("a wrong message was send");
			break;
		
		default:
		break;
		}
		return;
	}
	/**
	 * process sysmessages with category connection
	 * @param sysMessage message to process
	 */
	public void connection(SysMessage sysMessage){
		switch(sysMessage.getMessage()){
		case CONNECTED:										//server confirms that the client is connected
			System.out.println("connected to server "+server.getInetAddress()+" on port:"+server.getPort());	//tell that to the user
			break;
		case DISCONNECTED:									//a user disconnected
			System.out.println("["+sysMessage.getMessageString()+"] disconnected");	//tell that to the user
			break;
		case SERVER_CLOSED:
			System.out.println("server closed");
			break;
		
		default:
		break;
		}
		return;
	}
	/**
	 * process sysmessages with category login
	 * @param sysMessage message to process
	 */
	public void login(SysMessage sysMessage){
		switch(sysMessage.getMessage()){
		case LOGGED_IN:										//server confirms login
			System.out.println("your are now logged in");	//tell the user
			loadHistory();
			loggedIn=true;									//flag as logged in
			break;
		case NOT_LOGGED_IN:									//user is not logged in
			System.out.println("not logged in please log in or register");	//tell that to the user
			loggedIn=false;									//flag as logged out
			break;
		case ALREADY_LOGGED_IN:								//this client is already logged in
			System.out.println("you are already logged in");//tell the user
			break;
		case LOGGED_OUT:									//a user loggeged out
			System.out.println("["+sysMessage.getMessageString()+"] logged out");//tell the user
			break;
		case USER_ALREADY_LOGGED_IN:						//an other client is already logged in with this name
			System.out.println("this user is already logged in please try an other name");	//tell the user
			break;
		case REQUEST_USERNAME:								//server request the username
			sendSysMessage(CATEGORY.LOGIN,MESSAGE.SEND_USERNAME,username);	//send username to the server
			break;
		case USERNAME_UNKNOWN:								//Unknown username
			System.out.println("user unknown please register");				//requst an other name
			break;
		case USERNAME_BANNED:
			System.out.println("this user is banned from the server");
			break;
		case REQUEST_PASSWORD:								//server request password
			sendSysMessage(CATEGORY.LOGIN,MESSAGE.SEND_PASSWORD,password);	//send the password to the server
			break;
		case PASSWORD_WRONG:								//wrong password
			System.out.println("incorrect password please try to login again");	//request a new login
			break;

		
		default:
		break;
		}
		return;
	}
	/**
	 * process sysmessages with category registration
	 * @param sysMessage message to process
	 */
	public void registration(SysMessage sysMessage){
		switch(sysMessage.getMessage()){
		case REQUEST_NEW_USERNAME:						//request new username (after regristration)
			sendSysMessage(CATEGORY.REGISTRATION, MESSAGE.SEND_NEW_USERNAME, username);	//send the new name
			break;
		case USERNAME_ALREADY_EXISTS:						//username already in use (during registration process)
			System.out.println("username already in use try an other one");	//tell the user
			break;
		case REQUEST_NEW_PASSWORD:							//request new password (after regristration)
			sendSysMessage(CATEGORY.REGISTRATION, MESSAGE.SEND_NEW_PASSWORD, password);	//send new password
			break;
		case REGISTRATION_SUCCESSFUL:						//server confirms registration
			System.out.println("Your registration was successful. Please login now using your new username.");	//tell that to the user
			break;
		case TYPE_PASSWORD:
			String tempstr=null;
			tempstr=getPassword();
			System.out.println("4");
			System.out.println(tempstr);
			System.out.println("5");
			sendSysMessage(CATEGORY.LOGIN,MESSAGE.SEND_PASSWORD,tempstr);			//let the user type in the password
			break;
		
		default:
		break;
		}
		return;
	}
	/**
	 * process sysmessages with category change_username
	 * @param sysMessage message to process
	 */
	public void change_username(SysMessage sysMessage){
		switch(sysMessage.getMessage()){
		case REQUEST_CHANGED_USERNAME:						//request new password (after change of password)
			sendSysMessage(CATEGORY.CHANGE_USERNAME, MESSAGE.SEND_CHANGED_USERNAME, newusername);	//send the new password
			break;
		case USERNAME_CHANGED:								//somone has change his username
			if(sysMessage.getSenderUsername().equals("SERVER")){									//if sendername is server this client has changed his name
				System.out.println("your username was changed to "+sysMessage.getMessageString());	//tell the user
				renameHistory(sysMessage.getMessageString());										//rename history file
				username=sysMessage.getMessageString();												//save the new name
				newusername="";																		//reset 
			}else{																					//otherwise an other client changed his name
				System.out.println(sysMessage.getSenderUsername()+" changed his name to "+sysMessage.getMessageString());	//tell the user
			}
			break;
		case REQUEST_USERNAME:								//server request the username
			sendSysMessage(CATEGORY.LOGIN,MESSAGE.SEND_USERNAME,username);	//send username to the server
			break;
		case USERNAME_UNKNOWN:								//Unknown username
			System.out.println("user unknown please register");				//requst an other name
			break;
		case USERNAME_BANNED:
			System.out.println("this user is banned from the server");
			break;
		case REQUEST_PASSWORD:								//server request password
			sendSysMessage(CATEGORY.LOGIN,MESSAGE.SEND_PASSWORD,password);	//send the password to the server
			break;
		case PASSWORD_WRONG:								//wrong password
			System.out.println("incorrect password please try to login again");	//request a new login
			break;

		
		default:
		break;
		}
		return;
	}
	/**
	 * process sysmessages with category change_password
	 * @param sysMessage message to process
	 */
	public void change_password(SysMessage sysMessage){
		switch(sysMessage.getMessage()){
		case LOGIN_FIRST:
			System.out.println("you have to login to do this");
			break;
		case REQUEST_CHANGED_PASSWORD:
			sendSysMessage(CATEGORY.CHANGE_PASSWORD, MESSAGE.SEND_CHANGED_PASSWORD, newpassword);	//send the new password
			break;
		case PASSWORD_CHANGED:
			System.out.println("your password was changed");
			password=newpassword;
			newpassword="";
			break;
		case REQUEST_USERNAME:								//server request the username
			sendSysMessage(CATEGORY.LOGIN,MESSAGE.SEND_USERNAME,username);	//send username to the server
			break;
		case USERNAME_UNKNOWN:								//Unknown username
			System.out.println("user unknown please register");				//requst an other name
			break;
		case USERNAME_BANNED:
			System.out.println("this user is banned from the server");
			break;
		case REQUEST_PASSWORD:								//server request password
			sendSysMessage(CATEGORY.LOGIN,MESSAGE.SEND_PASSWORD,password);	//send the password to the server
			break;
		case PASSWORD_WRONG:								//wrong password
			System.out.println("incorrect password please try to login again");	//request a new login
			break;

		
		default:
		break;
		}
		return;
	}
	/**
	 * process sysmessages with category status
	 * @param sysMessage message to process
	 */
	public void status(SysMessage sysMessage){
		switch(sysMessage.getMessage()){
		case SEND_USER_LIST:								//server sends the list of user
			if (sysMessage.getMessageObject() instanceof String[]) {
				String[] userList = (String[]) sysMessage.getMessageObject();
				System.out.printf("Users currently logged in: %s\n", Arrays.toString(userList));	//prints list of user
			}
			break;
		case NEW_USER_INFO:									//info about new user connected
			System.out.println(sysMessage.getMessageString()+" just connected");	//tell the user
			break;
		case NO_ADMIN:
			System.out.println("you need to be a admin to do this");
			break;
		case NO_MOD:
			System.out.println("you need to be a moderator to do this");
			break;
		case YOU_ARE_REMOVED:
			System.out.println("you are no longer registerd on the server");
			break;
		case SEND_ROOM_LIST:
			if (sysMessage.getMessageObject() instanceof String[]) {
				String[] userList = (String[]) sysMessage.getMessageObject();
				System.out.printf("Romm currently available: %s\n", Arrays.toString(userList));	//prints list of rooms
			}
			break;
		case USER_KICKED:
			System.out.println("user "+sysMessage.getMessageString()+" was kicked by "+sysMessage.getSenderUsername());
			break;
		case BECOME_ADMIN:
			System.out.println("["+sysMessage.getMessageString()+"] is now admin");
			break;
		case BECOME_MOD:
			System.out.println("["+sysMessage.getMessageString()+"] is now moderator");
			break;
		case SEND_ADMIN_LIST:
			if (sysMessage.getMessageObject() instanceof String[]) {
				String[] userList = (String[]) sysMessage.getMessageObject();
				System.out.printf("The following users have admin rights: %s\n", Arrays.toString(userList));	//prints list of admins
			}
			break;
		case SEND_MOD_LIST:
			if (sysMessage.getMessageObject() instanceof String[]) {
				String[] userList = (String[]) sysMessage.getMessageObject();
				System.out.printf("The following users have moderator rights: %s\n", Arrays.toString(userList));	//prints list of admins
			}
			break;
		case SEND_ROLE:
			ROLE role =(ROLE)sysMessage.getMessageObject();
			switch(role){
			case ADMIN:
				System.out.println("you have admin rights");
				break;
			case MODERATOR:
				System.out.println("you have moderator rights");
				break;
			case STANDARD:
				System.out.println("you have standard rights");
				break;
			default:
				break;
			}
			break;

		default:
		break;
		}
		return;
	}
	/**
	 * process sysmessages with category admin
	 * @param sysMessage message to process
	 */
	public void admin(SysMessage sysMessage){
		switch(sysMessage.getMessage()){
		
		
		default:
		break;
		}
		return;
	}
	/**
	 * process sysmessages with category moderate
	 * @param sysMessage message to process
	 */
	public void moderate(SysMessage sysMessage){
		switch(sysMessage.getMessage()){
		case KICK_USER:
			if(sysMessage.getMessageString().equals(username)) {
				this.mainThread.isconnected = false;
				System.out.println("you are kicked by "+sysMessage.getSenderUsername());
			} else System.out.println("user "+sysMessage.getMessageString()+" was kicked by "+sysMessage.getSenderUsername());
			break;
		case BANN_USER:
			if(sysMessage.getMessageString().equals(username)) {
				this.mainThread.isconnected = false;
				System.out.println("you were banned from the server by "+sysMessage.getSenderUsername());
			} else System.out.println("user "+sysMessage.getMessageString()+" was banned from the server by "+sysMessage.getSenderUsername());
			break;
		case UNBANN_USER:
			if(sysMessage.getMessageString().equals(username))
				System.out.println("you were unbanned from the server by "+sysMessage.getSenderUsername());
			else System.out.println("user "+sysMessage.getMessageString()+" was unbanned from the server by "+sysMessage.getSenderUsername());
			break;

	
		
		default:
		break;
		}
		return;
	}
	
	/**
	 * save the history to a file
	 */
	public void saveHistory(){
		
		
		try {
			String relativpath=new File(".").getCanonicalPath();
			new File(relativpath+File.separatorChar+"history").mkdir();
			String filename=relativpath+File.separatorChar+"history"+File.separatorChar+username+".dat";
			File file=new File(filename);
			FileOutputStream f;
			ObjectOutputStream s;
			f = new FileOutputStream(file);
			s = new ObjectOutputStream(f);
			s.writeObject(msgArray);
			s.close();
		} catch (FileNotFoundException e1) {
			e1.printStackTrace();
			
		} catch (IOException e) {
			e.printStackTrace();
			
		}
		
		
		
		return;
	}
	/**
	 * loads history from file
	 */
	@SuppressWarnings("unchecked")
	public void loadHistory(){
		
		try {
			String relativpath=new File(".").getCanonicalPath();
			String filename=relativpath+File.separatorChar+"history"+File.separatorChar+username+".dat";
			File file=new File(filename);
			file.createNewFile();
			if(file.exists()){
				FileInputStream f = new FileInputStream(file);
			ObjectInputStream s = new ObjectInputStream(f);
			Object inputObject = s.readObject();
			
			if (inputObject instanceof List<?>)
				msgArray = (List<TextMessage>) inputObject;
			
			s.close();
			}
		} catch (IOException e) {
			//e.printStackTrace();
		} catch (ClassNotFoundException e) {
			//e.printStackTrace();
		}
		
		return;
	}
	/**
	 * prints the history to the screen
	 */
	public void showHistory(){
		DateFormat df;
		df = DateFormat.getDateTimeInstance( DateFormat.SHORT, DateFormat.SHORT );		//sets the time format
		if(msgArray!=null){																
		for(int i=0;i<msgArray.size();i++){												//loop through all messages
			if (msgArray.get(i).getReceived()!=null){									//check if message was sent or recieved
			System.out.println("->"+"["+df.format(msgArray.get(i).getReceived())+"]"+"["+msgArray.get(i).getSenderUsername()+"] "+msgArray.get(i).getMessageText());
			}else{
				System.out.println("<-"+"["+df.format(msgArray.get(i).getSent())+"]"+"["+msgArray.get(i).getSenderUsername()+"] "+msgArray.get(i).getMessageText());
			}
		}	
		}
		return;
	}
	/**
	 * removes the history file
	 */
	public void removeHistory(){
		String relativpath;
		try {
			relativpath = new File(".").getCanonicalPath();				//get the relative path
			String filename=relativpath+File.separatorChar+"history"+File.separatorChar+username+".dat";	//create filepath for the history
			File file=new File(filename);
			file.delete();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}	
		
		return;
	}
	/**
	 * rename the history 
	 * @param newname new name of the user
	 */
	public void renameHistory(String newname){
		String relativpath;
		try {
			relativpath = new File(".").getCanonicalPath();
			
		String filename=relativpath+File.separatorChar+"history"+File.separatorChar+username+".dat";
		File file=new File(filename);
		String newfilename="history"+File.separatorChar+newname+".dat";
		File newfile=new File(newfilename);
		file.renameTo(newfile);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return;
	}
	
}
		
